package com.jiexin.service;

import com.google.common.base.Preconditions;
import com.jiexin.beans.PageQuery;
import com.jiexin.beans.PageResult;
import com.jiexin.common.RequestHolder;
import com.jiexin.dao.SysUserMapper;
import com.jiexin.exception.ParamException;
import com.jiexin.model.SysUser;
import com.jiexin.param.UserParam;
import com.jiexin.util.BeanValidator;
import com.jiexin.util.IpUtil;
import com.jiexin.util.MD5Util;
import com.jiexin.util.PasswordUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: Jay_Liu
 * @Description:
 * @Date: Created in 11:00 2018/4/6 0006
 * @Modified By:
 */
@Service
public class SysUserService {

    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    SysLogService sysLogService;

    //新增用户
    public void save(UserParam param) {
        BeanValidator.check(param);
        if(checkTelePhoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExist(param.getMail(), param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        //默认给一个密码
        String password = PasswordUtil.randomPassword();
        //TODO:
        password = "12345678";
        String encryptedPassword = MD5Util.encrypt(password);
        SysUser sysUser = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .password(encryptedPassword).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();

        sysUser.setOperator(RequestHolder.getCurrentUser().getUsername());
        //根据当前请求，获取请求者的IP地址
        sysUser.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysUser.setOperateTime(new Date());

        //如果更新完后，邮箱发送失败，则密码则不知道
        // TODO:sendMail
        sysUserMapper.insertSelective(sysUser);
        sysLogService.saveUserLog(null, sysUser);

    }

    //更新用户
    public void update(UserParam param) {
        BeanValidator.check(param);
        if(checkTelePhoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExist(param.getMail(), param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        //更新前用户
        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的用户不存在");
        //更新后用户
        SysUser after = SysUser.builder().id(param.getId()).username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        //根据当前请求，获取请求者的IP地址
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        //有值则更新覆盖
        sysUserMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveUserLog(before, after);
    }

    public boolean checkEmailExist(String mail, Integer userId) {
        return sysUserMapper.countByMail(mail, userId) > 0 ;
    }

    public boolean checkTelePhoneExist(String telePhone, Integer userId) {
        return sysUserMapper.countByTelephone(telePhone, userId) > 0;
    }

    public SysUser findByKeyWord(String keyword) {
        return sysUserMapper.findByKeyword(keyword);
    }

    public PageResult<SysUser> getPageByDeptId(int deptId, PageQuery page) {
        BeanValidator.check(page);
        int count = sysUserMapper.countByDeptId(deptId);
        if (count > 0){
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    public List<SysUser> getAllUser() {
        return sysUserMapper.getAllUser();
    }


}
